package indi.mozping.protobufkafka;

import indi.mozping.protobufkafka.bean.User;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.ByteArrayDeserializer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

/**
 * @author by mozping
 * @Classname MyConsumer
 * @Description D:\protobuf\protoc.exe -I=D:\protobuf\proto --java_out=E:\    D:\protobuf\proto\User.proto
 * @Date 2019/7/20 16:49
 */
public class MyKafkaConsumer {

    private static Properties props = new Properties();

    private static boolean isClose = false;

    static {
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, Config.BROKER_LIST);
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "test18");
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class.getName());
    }

    public static void main(String args[]) {
        KafkaConsumer<String, byte[]> consumer = new KafkaConsumer<>(props);
        consumer.subscribe(Arrays.asList(Config.TOPIC_NAME));

        while (!isClose) {
            ConsumerRecords<String, byte[]> records = consumer.poll(Duration.ofMillis(100));
            if (records.isEmpty()) {
                System.out.println("Empty 不处理...");
            }
            for (ConsumerRecord<String, byte[]> record : records) {
                System.out.println("Key :" + record.key());
                System.out.printf("key = %s,offset=%s partition=%s value = %s%n", record.key(), record.offset(), record.partition(), new User(record.value()));
            }
        }

        consumer.close();
    }
}
